<?php
declare(strict_types=1);

namespace app\controller\api;

use app\controller\BaseController;
use app\model\MerchantApplication;
use app\service\WechatService;
use think\facade\{Cache, Log};

class WorkWechatController extends BaseController
{
    /**
     * 企业微信事件回调
     */
    public function callback($merchantId)
    {
        try {
            // 获取企业微信配置
            $appConfig = MerchantApplication::where([
                'merchant_id' => $merchantId,
                'application_type' => 4 // 企业微信通讯录
            ])->find();
            
            if (!$appConfig) {
                Log::error('企业微信配置不存在', ['merchant_id' => $merchantId]);
                return '';
            }
            
            $wechatService = new WechatService();
            $app = $wechatService->getWorkApp([
                'corp_id' => $appConfig->corp_id,
                'agent_id' => $appConfig->agent_id,
                'secret' => $appConfig->secret,
                'token' => $appConfig->token,
                'aes_key' => $appConfig->encoding_aes_key
            ]);
            
            $server = $app->server;
            
            // 处理群成员变更事件
            $server->push(function($message) use ($merchantId) {
                if ($message['MsgType'] === 'event' && $message['Event'] === 'change_external_chat') {
                    event('WorkChatMemberChange', [
                        'message' => array_merge($message, ['merchant_id' => $merchantId])
                    ]);
                }
                return '';
            });
            
            return $server->serve();
        } catch (\Exception $e) {
            Log::error('处理企业微信回调异常: ' . $e->getMessage());
            return '';
        }
    }
} 